package com.pth.dao.impl;

import java.sql.SQLException;
import java.util.Iterator;
import java.util.List;

import org.hibernate.HibernateException;
import org.hibernate.Session;
import org.springframework.orm.hibernate3.HibernateCallback;
import org.springframework.orm.hibernate3.HibernateTemplate;

import com.pth.dao.SignUpDAO;
import com.pth.model.SignUp;

public class SignUpDAOImpl implements SignUpDAO {

	private HibernateTemplate hibernateTemplate;
	
	public void save(SignUp signUp) {

		hibernateTemplate.save(signUp);
		
	}

	public HibernateTemplate getHibernateTemplate() {
		return hibernateTemplate;
	}

	public void setHibernateTemplate(HibernateTemplate hibernateTemplate) {
		this.hibernateTemplate = hibernateTemplate;
	}

	@SuppressWarnings("unchecked")
	public List<SignUp> getSignUpsByeid(final int pagesize,final int offset,int eid) {

		final String hql="from SignUp s where s.exam.eid="+eid;

		List<SignUp> list=hibernateTemplate.executeFind(new HibernateCallback() {

			public Object doInHibernate(Session arg0) throws HibernateException,
					SQLException {

				return arg0.createQuery(hql).setFirstResult(offset).setMaxResults(pagesize).list();
				
			}
		});
		
		return list;
		
		
	}

	public int getSignupNumByeid(int eid) {
		
		String hql="from SignUp s where s.exam.eid="+eid;
		return hibernateTemplate.find(hql).size();
		
	}

	@SuppressWarnings("unchecked")
	public SignUp getSignUpsBycard(String card,int eid) {

		String hqlString="from SignUp s where s.exam.eid="+eid+" and s.userinfo.identitycard='"+card+"'";
		List<SignUp> signUps =hibernateTemplate.find(hqlString);
		if(signUps.size()==0){
			
			return null;
		}
		
		Iterator<SignUp> iterators=signUps.iterator();
		SignUp signUp=new SignUp();
		while(iterators.hasNext()){
			
			signUp=iterators.next();
		}
		
		return signUp;
	}

	public void update(SignUp signUp) {

		hibernateTemplate.update(signUp);
	}

}
